package com.back.security;

import com.back.common.utils.GsonUtil;
import com.back.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义认证入口点
 * 当未认证的用户尝试访问需要认证的资源时，返回友好的JSON错误信息
 */
@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        
        log.warn("未认证的请求访问: {}, 错误: {}", request.getRequestURI(), authException.getMessage());
        
        // 设置响应状态和内容类型
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        
        // 构建错误响应
        Result result = Result.error()
                .code(HttpStatus.SC_UNAUTHORIZED)
                .message("请先登录后再访问");
        
        // 写入响应体
        try (PrintWriter writer = response.getWriter()) {
            writer.write(GsonUtil.toJson(result));
            writer.flush();
        }
    }
} 